<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8" />
  <title>组件配置器</title>
  <link rel="stylesheet" href="../vendor/bootstrap/dist/css/bootstrap.css" media="screen" title="no title" charset="utf-8" />
 </head>
 <body>
   {{#styles}}
  <link rel="stylesheet" href="./configure/styles/{{this}}" media="screen" title="no title" charset="utf-8" /> {{/styles}}
  <script src="../vendor/jquery/dist/jquery.js" charset="utf-8"></script>
  <script src="../vendor/bootstrap/dist/js/bootstrap.js" charset="utf-8"></script>
  <script src="../vendor/requirejs/require.js" charset="utf-8"></script>
  <script src="../../app.js" charset="utf-8"></script>
  <style>
    body {
      margin-top: 20px;
    }
    .nav > li > a {
      position: relative;
      display: block;
      padding: 5px 15px;
    }
    #config {
      height: 600px;
      border: none;
      background-color: inherit;
    }
    #sidebar {
      height: 700px;
      min-height: 700px;
      overflow-x: hidden;
      overflow-y: scroll;
    }
    .device {
      /*background-image: url("../images/device.png");*/
      width: 354px;
      height: 606px;
      margin: 0 auto;
      background-color: #ccc;
    }
    .device iframe.device-content {
      border: 0;
      left: 15px;
    }
    .device .device-content {
      position: relative;
      margin: 0 auto;
      top: 54px;
      width: 324px;
      height: 500px;
      overflow-y: auto;
      background: white;
    }
  </style>
  <div class="container-fluid">
   <div class="row">
    <div class="col-xs-3">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">组件清单</h3>
      </div>
      <div class="panel-body" id="sidebar">
       <ul id="com-list-ul" class="nav nav-pills nav-stacked">
         {{#components}}
        <!-- onclick="setActive(this);" -->
        <li data-name="{{this}}" role="presentation"><a href="javascript:null">{{this}}</a></li> {{/components}}
       </ul>
      </div>
     </div>
    </div>
    <div class="col-xs-7">
     <div class="panel panel-default">
      <div class="panel-heading">
       <ul class="nav nav-tabs">
        <li role="presentation" class="active"><a href="#preview" data-toggle="tab">预览</a></li>
        <li role="presentation"><a href="#tab2" data-toggle="tab">配置参数</a></li>
       </ul>
      </div>
      <div class="panelbody">
       <div class="tab-content">
        <div role="tabpanel" class="tab-pane active" id="preview">
         <div class="device">
          <iframe id="page-content" name="page-content" class="device-content" src="/inspectors/canvas.html"></iframe>
         </div>
        </div>
        <div role="tabpanel" id="tab2" class="tab-pane">
         <pre class=".pre-scrollable" id="config"></pre>
        </div>
       </div>
      </div>
     </div>
    </div>
    <div class="col-xs-2">
     <!-- <div class="panel panel-default">

          <div class="panel-heading">
            <h3 class="panel-title">配置器</h3>
          </div>
          <div class="panel-body">
            <div id="inspector"></div>
          </div>

          </div> -->
    </div>
   </div>
   <div id="modal"></div>
  </div>
  <script>
  function setActive(alink) {
        $('.nav > li').removeClass('active');
        $(alink).parent().addClass('active');
    }
    // all the inspectors was put in current directory
require.config({
    paths: {

        text: './vendor/requirejs-text/text',
        domReady: './vendor/requirejs-domready/domReady',
        i18n: './vendor/requirejs-i18n/i18n',
        hogan: './vendor/requirejs-hogan-plugin/hogan',
        hgn: './vendor/requirejs-hogan-plugin/hgn',

        // Backbone
        jquery: './vendor/jquery/dist/jquery',
        underscore: './vendor/underscore/underscore',
        backbone: './vendor/backbone/backbone',
        "backbone.paginator": "./vendor/backbone.paginator/lib/backbone.paginator",
        // react
        react: './vendor/react/react-with-addons',
        JSXTransformer: './vendor/react/JSXTransformer',
        jsx: './vendor/jsx-requirejs-plugin/js/jsx',
        // component dependency
        spin: './vendor/spinjs/spin',
        iscroll: './vendor/iscroll/build/iscroll',
        slick: './vendor/slick.js/slick/slick',
        imageLoader: '../../js/plugins/ImageLoader',
        binarytransport: '../../js/plugins/jquery.binarytransport',
        bootstrap: './vendor/bootstrap/dist/js/bootstrap',
        jcrop: './vendor/jcrop/js/jquery.Jcrop',
        Sortable: './vendor/Sortable/Sortable',
        slideout: "./vendor/slideout.js/dist/slideout.min"

    },
    jsx: {
        fileExtension: '.jsx'
    },
    shim: {
        "iscroll": {
            "exports": "IScroll"
        },
    }
    //waitSeconds: 20
});
require.onError = function (err) {
    console.log(err.requireType);
    if (err.requireType === 'timeout') {
        console.log('modules: ' + err.requireModules);
    }
    throw err;
};

require(['domReady!', 'backbone', 'react', 'jquery', './runtime/js/library', 'jsx', 'Sortable'],
    function (domReady, Backbone, React, $, library, jsx, Sortable) {
        window.library = library;
        var ComponentHandlerView = Backbone.View.extend({
            className: 'component-handle-view',
            events: {
                'click': 'selected',
                'click .del': 'onDelete'
            },
            selected: function () {
                    if (curSelectedComponent) {
                        curSelectedComponent.classList.remove("selected");
                    }
                    this.el.classList.add("selected");
                    curSelectedComponent = this.el;
                },
                initialize: function (options) {
                    this.options = _.pick(options, ['component', 'type']);
                    this.render();
                    this.setComponent(options.component);
                },
                render: function () {
                    this.$el.data('type', this.options.type);
                    this.$el.data('data-name', this.options.type);
                    this.$el.data('cid', this.cid);

                    this.$el.attr('data-type', this.options.type);
                    this.$el.attr('data-name', this.options.type);
                    this.$el.attr('data-cid', this.cid);

                    this.container = $('<div class="handler-content"></div>');
                    this.$el.append(this.container);
                    var extendDelClass = this.options.type !== "ContainerView" ? "" : "cv-del";
                    var del = $('<span style="z-index:121" class="del glyphicon glyphicon-trash ' + extendDelClass + '"></span>');
                    this.$el.append(del);
                    // 透明遮罩，在编辑器中防止点击到里面的元素
                    // xiaozhong_hu 容器支持嵌套拖拽 容器不加遮罩
                    if (!this.options.component.isContainer) {
                        this.mask = $('<div></div>').css({
                            position: "absolute",
                            top: 0,
                            bottom: 0,
                            left: 0,
                            zIndex:10,
                            right: 0,
                            'background-color': 'rgba(0, 0, 0, 0)'
                        });
                        this.$el.append(this.mask);
                    } else {
                        this.options.component.el.setAttribute("data-cid", this.cid);
                    }
                    return this;
                },
                remove: function () {
                    this.setComponent();
                    Backbone.View.prototype.remove.call(this, arguments);
                },
                setComponent: function (component) {
                    //remove former
                    this.component && this.component.remove();
                    //assign new
                    this.component = component;
                    //add to dom
                    if (component) {
                        this.container.append(component.el);
                        // 如果是全屏组件，则handler本身应该占满100%高度，通过css实现
                        if (component.fullScreen) this.$el.css({
                            height: '100%'
                        });
                    }

                },

                onDelete: function () {
                   delete handlers[this.cid];
                   $(this.el).remove();
                   getConfig();
                    //this.remove();
                    //this.trigger('delete', this);
                }
        });

        var Page = Backbone.Model.extend({

        });

        var Pages = Backbone.Collection.extend({
            model: Page,
            initialize: function (m, options) {
                this.app = options.app;
            }
        });

        var App = Backbone.Model.extend({
            initialize: function () {
                this.pages = new Pages([], this);
                this.id = (new Date()).valueOf();
            }
        });

        var app = new App();

        var sortable = new Sortable(document.getElementById("com-list-ul"), {
            group: {
                name: "name",
                pull: "clone"
            },
            draggable: "li",
            sort: false

        });
        var curSelectedComponent = null;
        var cid_wrapperComponent_dict = {};

        function getConfig() {
            var body = window.frames["page-content"].document.body;
            var childrennodes = body.childNodes;
            var config={"type":"PageView",components:[]};
            for (var i = 0,
                j = childrennodes.length; i < j; i++) {
                var c = childrennodes[i];
                var cid = c.getAttribute ? c.getAttribute("data-cid") : null;
                if (cid) {
                    var wrapper_com = handlers[cid];
                    if (wrapper_com) {
                        config.components.push(wrapper_com.component.getConfig())
                    }
                }
            }
            var opts = JSON.stringify(config, null, 2);
            $('#config').text(opts);
        }
        handlers={};
        function onSortInContainer(e){
          var to_cid = e.to.getAttribute("data-cid");
          var from_cid = e.from.getAttribute("data-cid");
          if(to_cid==from_cid){
                //同一个父容器中移动
            var parent_handle = handlers[to_cid];
            parent_handle.component.components=_getChildCompoents(parent_handle);
          }
          getConfig();
        }
        function onDragInContainer(e){

          var component_name = e.item.getAttribute("data-name");
          if (component_name) {

                var item_handle =handlers[e.item.getAttribute("data-cid")];
                var item_options ;
                if(item_handle){
                  item_options= item_handle.component.options;
                }
                var data_options =item_options|| {type:component_name};
                createHandler(component_name,
                function (handler) {
                    var to_cid = e.to.getAttribute("data-cid");
                    if(to_cid){
                      var to_handle = handlers[to_cid];
                      if(to_handle){
                        $(e.item).replaceWith(handler.el);
                        to_handle.component.components= _getChildCompoents(to_handle);
                      }
                    }

                   getConfig();
                },
                function () {
                    $(e.item).remove();
                });

              }
        }
        function _getChildCompoents(parent_handle){
          var new_component=[];
          var parent_childNodes= parent_handle.component.el.childNodes;
          for(var i =0,j=parent_childNodes.length;i<j;i++){
             var child_cid = parent_childNodes[i].getAttribute("data-cid");
             var child_handle = handlers[child_cid];
             new_component.push(child_handle.component);
          }
          return new_component;
        }

        function createHandler(component_name, success, error) {
            if (component_name) {
                var component_path = './runtime/js/components/' + component_name;
                require([component_path],
                    function (component_class) {
                        // try {
                            var component = new component_class;
                            var options = {
                                "type": component_name
                            };
                            component.compositeHandler = function (child) {
                                var childHandle = new ComponentHandlerView({
                                    type: child.type,
                                    /* TextView etc.*/
                                    component: child
                                });

                                if (child.DesignerCanDragIn) {
                                    new Sortable(child.el, {
                                        group: "name",
                                        onAdd: onDragInContainer,
                                        onSort: onSortInContainer
                                    });
                                }
                                handlers[childHandle.cid] = childHandle;
                                // _this.listenTo(childHandle, 'delete', _this.deleteComponent);
                                // _this.handlers[childHandle.cid] = childHandle;
                                return childHandle;
                            };
                            component.setOptions(options || {},
                                true); //TODO: 或许要干掉？
                            component.render();
                            // 组件控制器，包住控件，提供删除，拖拽什么的
                            var handler = new ComponentHandlerView({
                                type: options.type,
                                /* TextView etc.*/
                                component: component
                            });
                            handlers[handler.cid] = handler;
                            success(handler);
                        // } catch (ex) {
                        //     console.error(ex);
                        //     error();
                        // }
                    },
                    function (err) {

                    })

            }

        }

        var sortable1 = new Sortable(window.frames["page-content"].document.body, {
            group: "name",
            sort: true,
            draggable: ".component-handle-view",
            onAdd: function (e) {
                var component_name = e.item.getAttribute("data-name");
                createHandler(component_name,
                    function (handler) {
                        $(e.item).replaceWith(handler.el);
                      getConfig();
                    },
                    function () {
                        $(e.item).remove();
                    });
            },
            onSort:function(){
              getConfig();
          }

        });
    });
  </script>
 </body>
</html>
